<?php
namespace app\home\controller;
use \think\Cookie;
use think\Db;
use \think\View;
use \think\Model;
use \think\Request;
use \GatewayClient\Gateway;
class User extends Model
{
    protected $resultSetType = 'collection';
}

class Grade extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = false;
    protected $updateTime = false;
}

class StatusData extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = 'time';
    protected $updateTime = false;
}

class Sid extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = false;
    protected $updateTime = false;
}
class Gradepage extends \think\Controller
{
    function py_load($year, $term)
    {
        $cookie = Cookie::get('safecode');
        $person_data = User::getBySafecode($cookie);
        $uid = $person_data['Id'];
        $code = shell_exec('/www/server/panel/pyenv/bin/python python/main.py ' . $uid . ' ' . $year . ' ' . $term . ' 2>&1');
    }
    public function insert_sid()    //更改教务系统账号信息
    {
        $cookie = Cookie::get('safecode');
        $user = User::getBySafecode($cookie);
        $uid = $user['Id'];
        $status = new StatusData();
        $sid_data = Sid::getByUid($uid);
        if (input('post.')) {
            $sid_obj = new Sid();
            $sid = input('post.sid');
            $pwd = input('post.pwd');
            if (input('post.site')) {
                $site = input('post.site');
                $tmp = parse_url($site);
                if (isset($tmp['port'])) {
                    $site = $tmp['host'] . ':' . $tmp['port'];
                } else {
                    $site = $tmp['host'];
                }
            } else {
                $site = 'http://61.183.22.151:8080/';
            }
            if (empty($sid_data)) {
                $sid_obj->insert([
                    'sid' => $sid,
                    'pwd' => $pwd,
                    'uid' => $uid,
                    'site' => $site
                ]);
                $complete_site = 'http://' . $site . '/';
                $school = Db::name('school')->where('site', $complete_site)->find();
                if (!empty($school)) {
                    Db::name('school')->where('site', $complete_site)->setInc('num');
                } else {
                    Db::name('school')->insert(['school_name' => '未知大学', 'site' => $complete_site]);
                }
                $status->insert(['msg' => '他对接了教务系统', 'uid' => $uid, 'time' => date('Y-m-d H:i:s', time())]);
                $this->success('对接成功', 'insert_sid');
            } else {
                $sid_obj->where(['uid' => $uid])->update([
                    'sid' => $sid,
                    'pwd' => $pwd,
                    'site' => $site
                ]);
                $complete_site = 'http://' . $site . '/';
                $school = Db::name('school')->where('site', $complete_site)->find();
                if (!empty($school)) {
                    Db::name('school')->where('site', $complete_site)->setInc('num');
                } else {
                    Db::name('school')->insert(['school_name' => '未知大学', 'site' => $complete_site]);
                }
                $this->success('重新对接成功', 'insert_sid');
            }

        }
        if (empty($sid_data)) {
            $site = "";
            $sid = "";
            $pwd = "";
        } else {
            $site = 'http://' . $sid_data['site'] . '/';
            $sid = $sid_data['sid'];
            $pwd = $sid_data['pwd'];
        }
        $view = new View();
        $view->assign('site', $site);
        $view->assign('sid', $sid);
        $view->assign('pwd', $pwd);
        return $view->fetch('insert_sid', [], ['__PUBLIC__' => '/public/static']);
    }

    public function score()
    {    //获取成绩

        $view = new View();
        return $view->fetch('score', [], ['__PUBLIC__' => '/public/static']);
    }

    public function score_json()    //  成绩接口，对接bootstrap-table
    {    //获取成绩
        $cookie = Cookie::get('safecode');
        $user = User::getBySafecode($cookie)->toArray();
        $uid = $user['Id'];
        $sid = Sid::getByUid($uid);
        //获取用户信息
        $scores_obj = new Grade();
        //获取输入的年份和学期以确定输出的成绩数据
        if (input('get.year') && input('get.term')) {
            $this->py_load(input('post.year'), input('post.term'));
            $scores = $scores_obj->where(['uid' => $uid, 'year' => input('get.year'), 'term' => input('get.term')])->select()->toArray();
        } else {
            $scores = $scores_obj->where(['uid' => $uid])->where('is_sum', '<>', '1')->select()->toArray();
        }
        //对本学期数据进行处理

        $sum_score = 0;//假定一开始总分为0
        foreach ($scores as $score) {
            if (input('get.year') && input('get.term')) {
                if ($score['is_sum'] != 1) {//只要这个数据不是总分就计入总数据
                    $sum_score += $score['score'];
                }
            }
            //找出所有比自己成绩高的同学的成绩的个数以确定自己的名次（每一科）
            $num = Grade::where('class', 'LIKE', $score['class'])
                ->where('uid', '<>', $score['uid'])
                ->where('score', '>', $score['score'])
                ->where(['year' => $score['year'], 'term' => $score['term']])
                ->count();
            $sum_num = Grade::where('class', 'LIKE', $score['class'])
                ->where(['year' => $score['year'], 'term' => $score['term']])
                ->count();
            //更新每一科的名次
            $scores_obj->where('uid', $score['uid'])->where('class', $score['class'])->update(['order' => $num + 1]);
        }
        if (input('get.year') && input('get.term')) {
            $array = $scores_obj->where(['is_sum' => '1', 'uid' => $uid, 'year' => input('get.year'), 'term' => input('get.term')])->limit(1)->select()->toArray();
            //判断是否已经有总分的数据了
            if (!empty($array))//有就更新总分
            {

                if ($array[0]['score'] != (string)$sum_score) {
                    $scores_obj->where(
                        [
                            'is_sum' => '1',
                            'uid' => $uid,
                            'year' => input('get.year'),
                            'term' => input('get.term')
                        ])->update(['score' => $sum_score, 'get_time' => date('Y-m-d H:i:s', time())]);
                }

            } else {//没有就插入总分数据
                $scores_obj->insert(
                    [
                        'class' => '总分',
                        'is_sum' => '1',
                        'uid' => $uid,
                        'year' => input('get.year'),
                        'term' => input('get.term'),
                        'get_time' => time(),
                        'score' => $sum_score]);
            }
        }

        if (input('get.year') && input('get.term')) {
            $scores = $scores_obj->where(['uid' => $uid, 'year' => input('get.year'), 'term' => input('get.term')])->order('is_sum', 'asc')->select()->toArray();
        } else {
            $scores = $scores_obj->where(['uid' => $uid])->where('is_sum', '<>', '1')->select()->toArray();
        }
        $sum2 = (int)(($sum_num - 1) / 10);
        if ($sum2 == 0) {
            $sum2++;
        }
        $arr = [
            'code' => '200',
            'data' => $scores,
            'sum' => $sum_num,
            'sum2' => $sum2
        ];
        return json($arr);
    }

    public function site_json()     //  站点接口，对应联想搜索
    {
        $schools_data = Db::name('school')->select();
        $callback_data = [
            'code' => '200',
            'message' => '',
            'redirect' => '',
            'value' => $schools_data
        ];
        return json($callback_data);
    }
}